import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { verifyPassword, generateToken } from '@/lib/auth'

export async function POST(request: NextRequest) {
  try {
    let emailOrUsername: string
    let password: string

    // 支持JSON和表单数据
    const contentType = request.headers.get('content-type')
    if (contentType?.includes('application/json')) {
      const body = await request.json()
      emailOrUsername = body.emailOrUsername
      password = body.password
    } else {
      const formData = await request.formData()
      emailOrUsername = formData.get('emailOrUsername') as string
      password = formData.get('password') as string
    }

    console.log('登录请求:', { emailOrUsername, password: '***' })

    if (!emailOrUsername || !password) {
      return NextResponse.json(
        { error: '用户名/邮箱和密码不能为空' },
        { status: 400 }
      )
    }

    // 查找用户 - 支持邮箱或用户名登录
    const user = await prisma.user.findFirst({
      where: {
        OR: [
          { email: emailOrUsername },
          { username: emailOrUsername }
        ]
      }
    })

    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 401 }
      )
    }

    // 验证密码
    console.log('开始验证密码...')
    const isValidPassword = await verifyPassword(password, user.password)
    console.log('密码验证结果:', isValidPassword)

    if (!isValidPassword) {
      console.log('密码验证失败')
      return NextResponse.json(
        { error: '密码错误' },
        { status: 401 }
      )
    }

    console.log('密码验证成功，继续处理...')

    // 生成JWT token
    const token = await generateToken({
      id: user.id,
      email: user.email,
      username: user.username,
      role: user.role
    })

    // 创建响应并设置cookie
    const response = NextResponse.json({
      message: '登录成功',
      user: {
        id: user.id,
        email: user.email,
        username: user.username,
        role: user.role
      }
    })

    // 设置cookie（临时去掉HttpOnly用于调试）
    console.log('设置cookie，token长度:', token.length)

    response.cookies.set('auth-token', token, {
      httpOnly: false, // 临时设置为false用于调试
      secure: false,
      sameSite: 'lax',
      path: '/',
      maxAge: 7 * 24 * 60 * 60 // 7 days
    })

    console.log('Cookie设置完成')

    return response

  } catch (error) {
    console.error('Login error:', error)
    console.error('Error stack:', error instanceof Error ? error.stack : 'No stack trace')
    return NextResponse.json(
      { error: '服务器内部错误' },
      { status: 500 }
    )
  }
}
